# -*- coding: utf-8 -*-
import logging
### required - do no delete
def user(): return dict(form=auth())
def download(): return response.download(request,db)
def call():
    session.forget()
    return service()
### end requires
def index():
    form=SQLFORM(db.test)
    if form.accepts(request, session):
        response.flash='inserted'
    download = URL('download')
    records=SQLTABLE(db(db.test).select(db.test.ALL), upload=download)
    image=db().select(db.test.upload_test).last().upload_test
    logging.info('image:[%s]' % image)
    return dict(form=form,records=records,image=image)

class FileStream():
    def __init__(self, file):
        self.content = file
    def read(self):
        return self.content

def get():
    from gluon.tools import fetch
    #import urllib2
    #image_file = urllib2.urlopen('http://img3.douban.com/view/photo/photo/public/p364787203.jpg')
    image_file = fetch('http://img3.douban.com/view/photo/photo/public/p364787203.jpg')
    response.headers = {'Content-Type':'image/jpg'}
    response.status = 200
    image = FileStream(image_file)
    #record_id = db.test.insert(upload_test=db.test.upload_test.store2(file = image_file, filename ='test.jpg'))
    filename = db.test.upload_test.store2(file = image_file, filename ='test.jpg')
    keys = {'upload_test': filename,
            'upload_test_blob':image_file}
    db.test.insert(**keys)
    #db.test[record_id].update(**keys)
    return image.read()
    #return dict()

def show():
    response.headers = {'Content-Type':'image/jpeg'}
    response.status = 200
    return db.test[request.args[0]].upload_test_blob

def error():
    return dict()
